require('dotenv').config();
const express = require('express');
const cors = require('cors');
const http = require('http');
const WebSocket = require('ws');
const jwt = require('jsonwebtoken');
const httpProxies = require('./http/proxy');
const { httpRoutes, wsRoutes } = require('./config/routes');
const { handleWebSocketConnection } = require('./ws/proxy');
const { checkPermission } = require('./auth/routeGuards');
const { authMiddleware } = require('./auth/jwt'); // 添加此引用

const app = express();
const PORT = process.env.GATEWAY_PORT || 3000;

// 启用CORS
app.use(cors());

// 解析JSON请求体
app.use(express.json());

// 应用认证中间件
app.use(authMiddleware);

// 健康检查端点
app.get('/health', (req, res) => {
  res.status(200).json({ status: 'ok' });
});

// 公共API端点
app.get('/api/public', (req, res) => {
  res.status(200).json({ message: 'This is a public API' });
});

// 登录端点 - 生成JWT令牌
app.post('/api/auth/login', (req, res) => {
  const { username } = req.body;

  if (!username) {
    return res.status(400).json({ error: 'Username is required' });
  }

  // 生成JWT令牌
  const token = jwt.sign(
    { username: username },
    process.env.JWT_SECRET,
    { expiresIn: process.env.JWT_EXPIRES_IN }
  );

  res.status(200).json({ token });
});

// 刷新令牌端点
app.post('/api/auth/refresh', (req, res) => {
  const authHeader = req.headers.authorization;

  if (!authHeader || !authHeader.startsWith('Bearer ')) {
    return res.status(401).json({ error: '无效的令牌格式' });
  }

  const token = authHeader.split(' ')[1];

  try {
    // 验证令牌
    const decoded = jwt.verify(token, process.env.JWT_SECRET);

    // 生成新令牌
    const newToken = jwt.sign(
      { username: decoded.username },
      process.env.JWT_SECRET,
      { expiresIn: process.env.JWT_EXPIRES_IN }
    );

    res.status(200).json({ token: newToken });
  } catch (error) {
    res.status(401).json({ error: '无效的令牌' });
  }
});

// 路由到服务1
// 删除以下两行，使用循环注册路由
// app.use('/api/service1', service1Proxy);
// app.use('/api/service2', service2Proxy);

// 路由到服务3 (需要admin角色)
app.use('/api/service3', checkPermission('admin'), httpProxies['/api/service3']);

// 创建HTTP服务器
const server = http.createServer(app);

// 创建WebSocket服务器
const wss = new WebSocket.Server({ server });

// 处理WebSocket连接
handleWebSocketConnection(wss);

// 注册HTTP路由
httpRoutes.forEach(route => {
  app.use(route.path, httpProxies[route.path]);
});

// 启动服务器
server.listen(PORT, () => {
  console.log(`Gateway is running on port ${PORT}`);
  console.log(`Available routes:`);
  console.log(`- HTTP Health check: http://localhost:${PORT}/health`);
  console.log(`- HTTP Public API: http://localhost:${PORT}/api/public`);
  console.log(`- Login endpoint: http://localhost:${PORT}/api/auth/login`);
  console.log(`- Refresh token endpoint: http://localhost:${PORT}/api/auth/refresh`);
  httpRoutes.forEach(route => {
    console.log(`- HTTP ${route.name}: http://localhost:${PORT}${route.path}`);
  });
  wsRoutes.forEach(route => {
    console.log(`- ${route.name}: ws://localhost:${PORT}${route.path}`);
  });
});